<template>
  <div class="search">
    <div class="search-select">
      <el-select show-search size="small" placeholder="搜索聊天组" filterable remote reserve-keyword
        popper-class="search-select-popper" :remote-method="handleSearch" :loading="loading">
        <el-option v-for="(chat, index) in searchData" :key="index">
          <div v-if="chat.username">{{ chat.username }}
          </div>
          <div v-if="chat.groupName">{{ chat.groupName }}
          </div>
        </el-option>
      </el-select>
      <el-popover popper-class="search-add-popper" width="120px" placement="bottom" trigger="click"
        v-model:visible="visibleAddPopover">
        <template #reference>
          <span class="iconfont icon-cc-plus-square search-add-icon" @click="toggleVisiableAddPopover"></span>
        </template>
        <div class="search-add-item" @click="openVisibleDialog('addGroup')">创建群</div>
        <div class="search-add-item" @click="openVisibleDialog('searchGroup')">搜索群
        </div>
        <div class="search-add-item" @click="openVisibleDialog('searchUser')">搜索用户
        </div>
      </el-popover>
    </div>
    <el-dialog custom-class="search-dialog" v-model="visibleDialog" :title="dialogInfo[dialogStatus]['title']"
      width="45%" :close-on-click-modal="false">
      <div class="flex">
        <el-select v-if="dialogStatus === 'searchGroup'" show-search size="small" v-model="name" placeholder="搜索聊天组"
          filterable remote reserve-keyword class="searchGroupSelect" popper-class="search-select-popper"
          :remote-method="handleSearchGroup" :loading="loading">
          <el-option v-for="(group, index) in groupList" :key="index" :value="group.group_id" :label="group.group_name">
            <span style="float: left">{{ group.group_name }}</span>
            <span style="
              float: right;
              color:#666;
              font-size: 13px;">创建人:{{ group.creater }}</span>
          </el-option>
        </el-select>
        <input class="dialog-input" v-model="name" @keyup.enter="handleConfirm"
          :placeholder="dialogInfo[dialogStatus]['placeholder']" v-else />
        <button class="dialog-btn" @click="handleConfirm">{{dialogInfo[dialogStatus]['btn']}}</button>
      </div>
      <div class="add_friend_result" v-if="dialogStatus === 'searchUser'">
        <div v-for="friend in friendsList" :key="friend.user_id" class="add_friend_result_item">
          <div class="add_friend_result_item-head"><img :src="friend.avatar" /></div>
          <div class="add_friend_result_item-text">
            <p>{{ friend.realname }}</p>
            <button @click="handleAddFriend(friend)">+好友</button>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { defineComponent, ref, computed } from "vue";
import { Plus } from "@element-plus/icons-vue";
import {
  findPeopleService,
  insertFriendService,
  findGroupService,
  joinGroupService,
  createGroupService,
  getGroupService,
} from "../../../service/chat";
import socket from "../../../utils/socket_io";
import { useUserStore } from "../../../store/user";
import { useChatStore } from "../../../store/chat";
export default defineComponent({
  name: "chat-search",
  components: {
    Plus,
  },
  setup() {
    const loading = ref(false);
    const messgeList = ref([{ name: "a" }, { name: "b" }]);
    const userStore = useUserStore();
    const chatStore = useChatStore();
    const userInfo = computed(() => userStore.userInfo);
    const searchData = ref([]);
    const visibleDialog = ref(false);
    const visibleAddPopover = ref(false);
    const dialogStatus = ref("addGroup");
    const name = ref("");
    const friendsList = ref([]);
    const groupList = ref([]);
    const dialogInfo = ref({
      addGroup: {
        title: "创建群聊",
        btn: "确定",
        placeholder: "请输入群聊名称",
      },
      searchGroup: {
        title: "搜索群聊",
        btn: "添加群聊",
        placeholder: "请输入群聊名称",
      },
      searchUser: {
        title: "搜索用户",
        btn: "搜索",
        placeholder: "请输入用户名",
      },
    });
    const handleSearch = (query) => {
      if (query) {
        loading.value = true;
        setTimeout(() => {
          loading.value = false;
          searchData.value = messgeList.value.filter((item) => {
            return item.name.toLowerCase().indexOf(query.toLowerCase()) > -1;
          });
        }, 200);
      } else {
        searchData.value = [];
      }
    };
    const handleSearchGroup = (query) => {
      if (query) {
        loading.value = true;
        findGroupService({ group_name: query }).then((res) => {
          loading.value = false;
          groupList.value = res.data;
        });
      } else {
        groupList.value = [];
      }
    };
    const openVisibleDialog = (status) => {
      name.value = "";
      dialogStatus.value = status;
      visibleDialog.value = true;
      visibleAddPopover.value = false;
      friendsList.value = [];
      groupList.value = [];
    };
    const handleConfirm = () => {
      if (!name.value) {
        ElMessage.error("请输入搜索数据");
        return;
      }
      switch (dialogStatus.value) {
        case "addGroup":
          createGroupService({ group_name: name.value }).then((res) => {
            visibleDialog.value = false;
            handleGetGroupList();
          });
          break;
        case "searchGroup":
          handleAddGroup();
          break;
        case "searchUser":
          findPeopleService({ realname: name.value }).then((res) => {
            friendsList.value = res.data;
          });
          break;
        default:
          break;
      }
    };
    const handleAddFriend = (friend) => {
      let content = `你好,我是${userInfo.value.realname}`;
      insertFriendService({ to: friend.user_id, content }).then((res) => {
        ElMessage.success("已发送添加好友请求");
        visibleDialog.value = false;
        socket.emit("sendRequest", friend);
      });
    };
    const handleAddGroup = (group) => {
      joinGroupService({
        user_id: userInfo.value.user_id,
        group_id: name.value,
      })
        .then((res) => {
          visibleDialog.value = false;
          socket.emit("sendRequest", friend);
          handleGetGroupList();
        })
        .catch((err) => {
          visibleDialog.value = false;
        });
    };
    const handleGetGroupList = () => {
      getGroupService().then((res) => {
        chatStore.groupListAction(res.data);
      });
    };
    const toggleVisiableAddPopover = () => {
      visibleAddPopover.value = !visibleAddPopover.value;
    };
    return {
      loading,
      messgeList,
      searchData,
      visibleDialog,
      dialogInfo,
      dialogStatus,
      name,
      visibleAddPopover,
      friendsList,
      groupList,
      userInfo,
      handleSearch,
      toggleVisiableAddPopover,
      handleSearchGroup,
      openVisibleDialog,
      handleConfirm,
      handleAddFriend,
      handleAddGroup,
    };
  },
});
</script>

<style lang="less" scoped>
.search {
  background: #fbfbfb;
  position: relative;
  height: 60px;
  padding: 10px;
  display: flex;
  align-items: center;
  .search-select {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .el-select {
      flex: 0 0 206px;
      :deep(.el-input__inner) {
        background-color: white;
        color: #606266;
        border: 1px solid #d9d9d9;
        &:hover {
          border-color: #2ac769;
        }
      }
    }
    .search-add-icon {
      display: inline-block;
      font-size: 26px;
      transition: 0.2s all linear;
      border-radius: 4px;
      cursor: pointer;
      color: gray;
      &:hover {
        color: #2ac769;
      }
    }
  }
}
</style>
<style lang="less">
.dark-theme {
  .search-select-popper {
    &.el-popper[role="tooltip"] {
      background: white;
      border-color: #e5e7eb;
    }
    color: #303133;
    .el-select-dropdown__item {
      color: #606266;
      &:hover,
      &.hover {
        background-color: #f5f7fa;
      }
    }
    &.el-popper[role="tooltip"] {
      border-color: #e5e7eb;
    }
    &.is-light.el-popper[role="tooltip"] .el-popper__arrow:before {
      border-color: rgb(228, 231, 237);
      background: white;
    }
  }
  .search-add-popper {
    &.el-popper[role="tooltip"] {
      min-width: 100px;
      background: white;
      color: #303133;
      border-color: #e5e7eb;
    }
    &.is-light.el-popper[role="tooltip"] .el-popper__arrow:before {
      border-color: rgb(228, 231, 237);
      background: white;
    }
    .search-add-item {
      line-height: 22px;
      padding: 5px 16px;
      color: #606266;
      cursor: pointer;
      outline: none;
      &:hover {
        color: #2ac769;
      }
    }
  }
  .search-dialog {
    background-color: white;
    .el-dialog__title {
      color: #303133;
      font-size: 18px;
      font-weight: 500;
    }
    .el-dialog__headerbtn .el-dialog__close {
      color: #909399;
      &:hover {
        color: #2ac769;
      }
    }
    .dialog-input {
      flex: 1;
      box-sizing: border-box;
      margin: 0;
      padding: 0;
      font-variant: tabular-nums;
      list-style: none;
      font-feature-settings: "tnum";
      position: relative;
      display: inline-block;
      height: 32px;
      padding: 4px 11px;
      color: rgba(0, 0, 0, 0.65);
      font-size: 14px;
      line-height: 1.5;
      background-color: #fff;
      background-image: none;
      border: 1px solid #d9d9d9;
      border-radius: 4px;
      transition: all 0.3s;
      &:hover {
        border-color: #09b955;
      }
    }
    .dialog-btn {
      margin: 0 12px;
      color: #fff;
      background-color: #09b955;
      border-color: #09b955;
      text-shadow: 0 -1px 0 rgb(0 0 0 / 12%);
      line-height: 1.499;
      position: relative;
      display: inline-block;
      font-weight: 400;
      white-space: nowrap;
      text-align: center;
      background-image: none;
      border: 1px solid transparent;
      box-shadow: 0 2px 0 rgb(0 0 0 / 2%);
      cursor: pointer;
      transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
      user-select: none;
      touch-action: manipulation;
      height: 32px;
      padding: 0 15px;
      font-size: 14px;
      border-radius: 4px;
    }
    .add_friend_result {
      padding-left: 12px;
      margin-top: 30px;
      display: flex;
      align-content: center;
      align-items: center;
      justify-content: start;
      flex-wrap: wrap;

      .add_friend_result_item {
        flex: 0 0 250px;
        background-color: #ffffff;
        box-shadow: rgba(0, 0, 0, 0.1) 0px 2px 12px 0px;
        margin: 8px;
        padding: 10px;
        display: flex;
        align-items: center;

        .add_friend_result_item-head {
          flex: 0 0 36px;
          height: 36px;

          & > img {
            width: 36px;
            border-radius: 50%;
          }
        }

        .add_friend_result_item-text {
          flex: 1;
          padding-left: 12px;
          max-width: 194px;
          width: 194px;

          & > p {
            padding-bottom: 16px;
            font-size: 14px;
            color: #000;
            font-weight: 500;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }

          & > button {
            background: #18caff;
            border: 0;
            font-size: 12px;
            border-radius: 4px;
            padding: 4px 6px;
            color: white;
            cursor: pointer;
          }
        }
      }
    }
  }
}
</style>
<style lang="less">
.dark-theme {
  .searchGroupSelect {
    width: 100%;
    input {
      background-color: white;
      color: #606266;
      border: 1px solid #d9d9d9;
      &:hover {
        border-color: #2ac769;
      }
    }
  }
}
</style>